package me.itsoo.elasticbatis.io;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.SneakyThrows;

import java.io.File;
import java.io.IOException;
import java.net.JarURLConnection;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

/**
 * ResolverUtil
 *
 * @author zhangxy4
 * @version 0.0.1
 * @since 2025/4/3
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class ResolverUtil {
    private static final String FILE_PROTOCOL = "file";
    private static final String JAR_PROTOCOL = "jar";

    private static final String CLASS_SUFFIX = ".class";
    private static final String DOT_STR = ".";
    private static final char DOT_CHR = '.';
    private static final char SPR_CHR = '/';


    /**
     * 根据提供的包名，扫描所有的类
     *
     * @param packageName 包名
     * @return 类集合
     */
    @SneakyThrows({IOException.class, ClassNotFoundException.class})
    public static Set<Class<?>> findClasses(String packageName) {
        Set<Class<?>> classSet = new HashSet<>();

        String path = packageName.replace(DOT_CHR, SPR_CHR);
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        Enumeration<URL> resources = classLoader.getResources(path);

        while (resources.hasMoreElements()) {
            URL resource = resources.nextElement();
            if (FILE_PROTOCOL.equals(resource.getProtocol())) {
                File directory = new File(resource.getFile());
                if (directory.exists()) {
                    findClassesInDirectory(directory, packageName, classSet);
                }
            } else if (JAR_PROTOCOL.equals(resource.getProtocol())) {
                findClassesInJar(resource, packageName, classSet);
            }
        }

        return classSet;
    }

    /**
     * 递归查找目录中的类
     *
     * @param directory   要查找的目录
     * @param packageName 当前包名
     * @param classSet    类集合
     * @throws ClassNotFoundException ClassNotFoundException
     */
    private static void findClassesInDirectory(File directory, String packageName, Set<Class<?>> classSet)
            throws ClassNotFoundException {

        File[] files = directory.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isDirectory()) {
                    assert !file.getName().contains(DOT_STR);
                    findClassesInDirectory(file, packageName + DOT_STR + file.getName(), classSet);
                } else if (file.getName().endsWith(CLASS_SUFFIX)) {
                    int removeSuffix = file.getName().length() - CLASS_SUFFIX.length();
                    String className = packageName + DOT_STR + file.getName().substring(0, removeSuffix);
                    classSet.add(Class.forName(className));
                }
            }
        }
    }

    /**
     * 查找jar包中的类
     *
     * @param resource    jar路径
     * @param packageName 要查找的包名
     * @param classSet    类集合
     * @throws IOException            IOException
     * @throws ClassNotFoundException ClassNotFoundException
     */
    private static void findClassesInJar(URL resource, String packageName, Set<Class<?>> classSet)
            throws IOException, ClassNotFoundException {

        JarURLConnection jarUrlConn = (JarURLConnection) resource.openConnection();
        JarFile jarFile = jarUrlConn.getJarFile();
        Enumeration<JarEntry> entries = jarFile.entries();
        while (entries.hasMoreElements()) {
            JarEntry entry = entries.nextElement();
            String name = entry.getName();
            if (name.startsWith(packageName.replace(DOT_CHR, SPR_CHR)) && name.endsWith(CLASS_SUFFIX)) {
                int removeSuffix = name.length() - CLASS_SUFFIX.length();
                String className = name.replace(SPR_CHR, DOT_CHR).substring(0, removeSuffix);
                classSet.add(Class.forName(className));
            }
        }
    }
}
